package com.hb.unic.core.async.impl;

import java.util.LinkedList;
import java.util.List;
import java.util.Optional;

import org.springframework.stereotype.Component;

import com.hb.unic.core.async.IMessageChannel;
import com.hb.unic.core.async.IMessageProcessor;
import com.hb.unic.core.context.Application;
import com.hb.unic.core.context.handler.IAfterStartupHandler;
import com.hb.unic.core.context.event.StartupEventArgs;

/**
 * 异步消息上下文初始化处理器
 *
 * @since v1.0，2023/8/28 23:03，create by Mr.Huang.
 */
@Component
public class MessageConfigManager implements IAfterStartupHandler {

    /**
     * 管道配置
     */
    private static List<MessageChannelConfig> channelConfigs;

    /**
     * 处理器配置
     */
    private static List<MessageProcessorConfig> processorConfigs;

    @Override
    public void execute(StartupEventArgs eventArgs) {
        // 设置消息通道配置
        channelConfigs = Application.getContext().getBeanList(MessageChannelConfig.class);
        // 设置处理器配置
        processorConfigs = Application.getContext().getBeanList(MessageProcessorConfig.class);
    }

    /**
     * 获取管道
     * 
     * @param messageType 消息类型
     * @return 管道
     */
    public static IMessageChannel getChannel(String messageType) {
        Optional<MessageChannelConfig> channelConfig =
            channelConfigs.stream().filter(channel -> channel.getMessageType().equals(messageType)).findFirst();
        return channelConfig.map(MessageChannelConfig::getChannel).orElse(null);
    }

    /**
     * 获取处理器
     * 
     * @param messageType 消息类型
     * @return 处理器
     */
    public static List<IMessageProcessor> getProcessors(String messageType) {
        Optional<MessageProcessorConfig> channelConfig =
            processorConfigs.stream().filter(processor -> processor.getMessageType().equals(messageType)).findFirst();
        return channelConfig.map(MessageProcessorConfig::getProcessors).orElse(new LinkedList<>());
    }

}
